package com.alibaba.algo.domain.user;

import com.alibaba.algo.cooperation.feign.vo.req.SelectRoleByOrgVO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.SysOrgInfoVO;
import com.alibaba.algo.core.base.BaseDomain;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.dao.user.SysOrgRoleMapper;
import com.alibaba.algo.entity.user.SysOrgRole;
import com.alibaba.algo.entity.user.SysRole;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * 组织和组织角色关联Domain
 */
@Component
public class SysOrgRoleDomain extends BaseDomain<SysOrgRole> {

    @Resource
    private SysOrgRoleMapper sysOrgRoleMapper;

    /**
     * 更新关联关系，策略是找出需要删除的关系进行删除，找出需要新增的关系进行新增
     */
    public void updateRelatedByRoleId(Long roleId, List<Long> orgIdList) {
        //现有的关系
        SysOrgRole param = new SysOrgRole();
        param.setRoleId(roleId);
        List<SysOrgRole> currentList = this.listByPara(param, null);

        if (!ObjectUtils.isEmpty(orgIdList)) {
            out:
            for (Long orgId : orgIdList) {
                if(null != orgId){
                    if (currentList != null) {
                        Iterator<SysOrgRole> iterator = currentList.iterator();
                        while (iterator.hasNext()) {
                            SysOrgRole temp = iterator.next();
                            if (orgId.equals(temp.getOrgId())) {
                                iterator.remove();
                                continue out;
                            }
                        }
                    }
                    SysOrgRole temp = new SysOrgRole();
                    temp.setRoleId(roleId);
                    temp.setOrgId(orgId);
                    this.insert(temp);
                }
            }
        }
        if (currentList != null) {
            for (SysOrgRole temp : currentList) {
                temp.setIsDeleted(YesOrNo.Y.name());
                this.updateById(temp);
            }
        }
    }

    public void deleteByRoleId(Long roleId) {
        sysOrgRoleMapper.deleteByRoleId(roleId);
    }

    public Integer updateByRoleId(SysOrgRole sysOrgRole){
        return sysOrgRoleMapper.updateByRoleId(sysOrgRole);
    }

    public List<SysOrgInfoVO> selectOrgListByRoleId(Long roleId) {
        return sysOrgRoleMapper.selectOrgListByRoleId(roleId);
    }


    public List<SysRole> selectRoleListByOrgCondition(SelectRoleByOrgVO vo){
        return sysOrgRoleMapper.selectRoleListByOrgCondition(vo);
    }
}
